import Taro from "@tarojs/taro";
import React, { useState, useRef, useEffect } from "react";
import { View, Map, Image } from "@tarojs/components";
import { MapProps } from "@tarojs/components/types/Map";
import ChinaMap from "./ChinaMap";

import add_boldPNG from "../../static/add-bold.png";
import minus_boldPNG from "../../static/minus-bold.png";
import airportPNG from "../../static/airport.png";
import locationPNG from "../../static/location.png";
import airport2PNG from "../../static/airport2.png";
import "./index.scss";
import {
  IregeoResponse,
  IsearchPOIResponse,
  Iregeocode,
  IPoint
} from "../../interface";
import { request } from "../../utils";
import Config from "../../Config";

interface ISize {
  width: number;
  height: number;
}
const presetScale = 4;

function MapPage() {
  const [position, setPosition] = useState({
    latitude: 34.76,
    longitude: 113.65
  });

  const [showScale, setShowScale] = useState(presetScale);
  const [markers, setMarkers] = useState<MapProps.marker[]>([]);
  const [centerGeo, setCenterGeo] = useState<Iregeocode>();
  const [showAirports, setShowAirports] = useState(false);
  const [step, setStep] = useState(0);
  // const [enableZoom, setEnableZoom] = useState(false);

  const mapContext = useRef<Taro.MapContext>();
  const realScale = useRef(showScale);

  useEffect(() => {
    Taro.onAppHide(() => {
      console.log("隐藏");
    });
  }, []);

  async function handleUpdated() {
    if (mapContext.current === undefined) {
      mapContext.current = Taro.createMapContext("myMap");
      console.log("首次渲染完");
      const centerLocation = await mapContext.current.getCenterLocation();

      handleCenterLocation(centerLocation);
    }
    // if (step === 1 && systemInfo.current) {
    //   setScrollViewScroll({
    //     x: systemInfo.current.windowWidth,
    //     y: systemInfo.current.windowHeight
    //   });
    //   setStep(2);
    // }

    // if (mapContext.current) {
    //   const centerLocation = await mapContext.current.getCenterLocation();
    //   let region: Iregion = (await mapContext.current.getRegion()) as any;
    //   console.log(centerLocation, region);
    // }

    // if (bigRegion.current === undefined) {
    //   const region: Iregion = (await mapContext.current.getRegion()) as any;
    //   bigRegion.current = {
    //     dLat: region.northeast.latitude - region.southwest.latitude,
    //     dLog: region.northeast.longitude - region.southwest.longitude,
    //   };
    // }
  }

  async function getAirData(geoData) {
    const { province } = geoData.addressComponent;
    if (province.length > 0 && typeof province === "string") {
      const { data: airData = {} } =
        (await Taro.getStorage({ key: "airData" }).catch(() => {})) || {};
      let provinceAirData: IsearchPOIResponse = airData[province];
      if (provinceAirData === undefined) {
        const searchResult = await request<IsearchPOIResponse>(Config.搜索POI, {
          // keyword: "机场|飞机场",
          types: 150104,
          city: province
        });
        if (Number(searchResult.status) === 1) {
          provinceAirData = searchResult;
          airData[province] = searchResult;
          Taro.setStorage({
            key: "airData",
            data: airData
          });
        } else {
          Taro.showModal({
            title: "提示",
            content: searchResult.info
          });
        }
      }

      console.log({ province }, { provinceAirData }, { airportPNG });

      setMarkers(
        provinceAirData.pois.map((poi, id) => ({
          latitude: Number(poi.location.split(",")[1]),
          longitude: Number(poi.location.split(",")[0]),
          width: 20,
          height: 20,
          iconPath: airportPNG,
          id,
          // title: poi.name,
          // anchor: { x: 1, y: 0 },
          label: {
            content: poi.name, //文本
            color: "#1296db", //文本颜色
            borderRadius: 5, //边框圆角
            borderWidth: 1, //边框宽度
            borderColor: "#1296db", //边框颜色
            bgColor: "#fff", //背景色
            padding: 5, //文本边缘留白
            textAlign: "center", //文本对齐方式。有效值: left, right, center
            anchorX: 0,
            anchorY: 0,
            fontSize: 11,
            x: 0,
            y: 0
          }
        }))
      );
    }
  }

  async function handleCenterLocation(
    centerLocation: Taro.MapContext.GetCenterLocationSuccessCallbackResult
  ) {
    const geoData = await getCenterGeo(centerLocation);
    console.log({ geoData });

    getAirData(geoData);
    setCenterGeo(geoData);
  }
  async function regionHandler(event: MapProps.onRegionChangeEventDetail) {
    const { type, causedBy } = event;
    if (causedBy === "drag" || causedBy === "gesture") {
      // Taro.showToast({
      //   title: type,
      //   duration: 1000
      // });
      // setTimeout(() => {
      //   if (mapContext.current) {
      //     mapContext.current.moveToLocation({
      //       latitude: 23.96617587126503,
      //       longitude: 113.642578125
      //     });
      //   }
      // }, 1000);
      console.log("drag", event);
    }

    if (type === "end" && mapContext.current) {
      realScale.current = (await mapContext.current.getScale()).scale;
      const centerLocation = await mapContext.current.getCenterLocation();

      const Rerender = causedBy !== "update";
      if (Rerender) {
        setPosition({
          latitude: centerLocation.latitude,
          longitude: centerLocation.longitude
        });
        handleCenterLocation(centerLocation);
      }
    }
  }
  async function getCenterGeo(
    centerLocation: Taro.MapContext.GetCenterLocationSuccessCallbackResult
  ) {
    const regeoData = await request<IregeoResponse>(Config.逆地理编码, {
      location: `${centerLocation.longitude},${centerLocation.latitude}`
    });

    return regeoData.regeocode;
  }
  function handleZoomClick() {
    const num = this === "+" ? 1 : -1;
    realScale.current += num;
    setShowScale(realScale.current);
  }
  function handleAirports() {
    if (step === 0 && !showAirports) {
      setStep(1);
    } else if (step === 1 && showAirports) {
      setStep(2);
    }
    setShowAirports(oldShow => !oldShow);
  }
  function handleMapTap(e) {
    console.log("点击", { e });
  }

  let myMarkers = showAirports ? markers : [];

  const centerLocationTitle = centerGeo
    ? centerGeo.addressComponent.city +
      (centerGeo.addressComponent.district.length > 0
        ? centerGeo.addressComponent.district
        : centerGeo.addressComponent.township)
    : "";

  return (
    <View className="MapPage">
      {step <= 1 && (
        <Map
          className="MapPage-Map"
          // style={mapStyle}
          scale={showScale}
          enableZoom
          enableScroll
          latitude={position.latitude}
          longitude={position.longitude}
          // @ts-ignore
          onEnd={regionHandler}
          // @ts-ignore
          onBegin={regionHandler}
          id="myMap"
          onUpdated={handleUpdated}
          onTap={handleMapTap}
          markers={myMarkers}
          showLocation
        ></Map>
      )}
      {step > 1 && (
        <ChinaMap
          enableScroll={step !== 0}
          latitude={position.latitude}
          longitude={position.longitude}
        />
      )}
      {centerGeo && centerLocationTitle && (
        <View className="LocationNameView">
          <View className="Title">{centerLocationTitle}</View>
        </View>
      )}
      <View className="LocationView">
        <Image className="Location" src={locationPNG} />
      </View>
      <View className="ControlView">
        <Image
          className="Button"
          src={showAirports ? airportPNG : airport2PNG}
          onClick={handleAirports}
        />
      </View>
      <View className="ZoomView">
        <Image
          className="Button"
          src={add_boldPNG}
          onClick={handleZoomClick.bind("+")}
        />
        <Image
          className="Button"
          src={minus_boldPNG}
          onClick={handleZoomClick.bind("-")}
        />
      </View>
    </View>
  );
}
export default MapPage;
